#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import json
import db_conf
import urllib2
import time

print time.asctime( time.localtime(time.time()) )
con = None

try:
    s = None
    metid = "C00029"
    stream = urllib2.urlopen("http://rest.kegg.jp/get/" + metid).read() 
    print time.asctime( time.localtime(time.time()) ) + " fetching\n" + "http://rest.kegg.jp/get/" + metid
    #config = db_conf.getConfig('metabvis.conf')
    #con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    #cur = con.cursor()
    select_experiments = "SELECT e.experiment_id, experimenter, date, description, organism_text, sample_type_text, count(c.chromatogram_id) as files from experiment e, organism o, sample_type s, chromatogram c where e.organism_id = o.organism_id and e.sample_type_id = s.sample_type_id and e.experiment_id = c.experiment_id GROUP BY e.experiment_id, experimenter, date, description, sample_type_text, organism_text order by e.experiment_id"
    #cur.execute(select_experiments)          
    #rows = cur.fetchall()
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    pa['aaData'] = stream.split("\n")
    print json.dumps(pa)
    print time.asctime( time.localtime(time.time()) )
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    
    if con:
        con.close()
